<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form :labelCol="labelCol" :wrapperCol="wrapperCol" ref="queryForm">
          <a-row :gutter="32">
            <a-col :span="6" v-hasPermi="['platform:region:add']">
              <a-form-item label="用户">
                <select-user v-model="queryParam.userId" select-model="single" placeholder="请选择用户" />
              </a-form-item>
            </a-col>
            <a-col :span="6" v-hasPermi="['platform:region:add']">
              <a-form-item label="地区">
                <select-region v-model="queryParam.regionId" placeholder="请选择地区" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="版块">
                <select-section v-model="queryParam.sectionId" placeholder="请选择版块" />
              </a-form-item>
            </a-col>
            <a-col :span="6" v-if="advanced || roleControlQuery">
              <a-form-item label="帖子标题">
                <a-input v-model="queryParam.title" placeholder="请输入帖子标题" allow-clear @keyup.enter.native="handleQuery" />
              </a-form-item>
            </a-col>
            <a-col :span="6" v-if="advanced || roleControlQuery">
              <a-form-item label="帖子内容">
                <a-input v-model="queryParam.content" placeholder="请输入帖子内容" allow-clear @keyup.enter.native="handleQuery" />
              </a-form-item>
            </a-col>
            <a-col :span="6" v-if="advanced">
              <a-form-item label="匿名状态">
                <a-radio-group v-model="queryParam.anonymity" style="margin-top: 5px">
                  <a-radio v-for="(dict, index) in anonymityOptions" :key="index" :value="dict.dictValue" @click="radioAgain(dict.dictValue)">
                    {{ dict.dictLabel }}
                  </a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="6" v-if="advanced">
              <a-form-item label="帖子类型">
                <a-select placeholder="请选择帖子类型" v-model="queryParam.type" style="width: 100%" allow-clear>
                  <a-select-option v-for="(d, index) in typeOptions" :key="index" :value="d.dictValue">{{ d.dictLabel }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6" v-if="advanced">
              <a-form-item label="帖子状态">
                <a-select placeholder="请选择帖子状态" v-model="queryParam.status" style="width: 100%" allow-clear>
                  <a-select-option v-for="(d, index) in statusOptions" :key="index" :value="d.dictValue">{{ d.dictLabel }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col>
              <span class="table-page-search-submitButtons" style="float: right">
                <a-button type="primary" @click="handleQuery"><a-icon type="search" />查询</a-button>
                <a-button style="margin-left: 8px" @click="resetQuery"><a-icon type="redo" />重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" class="table-card">
      <!-- 增加 -->
      <post-add-form v-if="showAddModal" ref="postAddForm" :statusOptions="statusOptions" :anonymityOptions="anonymityOptions" :typeOptions="typeOptions" @ok="getList" @close="showAddModal = false" />
      <!-- 编辑 -->
      <post-edit-form v-if="showEditModal" ref="postEditForm" :statusOptions="statusOptions" :anonymityOptions="anonymityOptions" :typeOptions="typeOptions" @ok="getList" @close="showEditModal = false" />
      <!-- 审核记录 -->
      <approve-record-table-modal v-if="showApproveRecordTableModal" ref="approveRecordTableModal" @ok="getList" @close="showApproveRecordTableModal = false" :itemId="postId" :statusOptions="statusOptions" />
      <!-- 评论管理 -->
      <comment-table-modal v-if="showCommentTableModal" ref="commentTableModal" @ok="getList" @close="showCommentTableModal = false" :itemId="postId" />
      <advance-table
        title="帖子管理"
        :pagination="{
          current: queryParam.pageNum,
          pageSize: queryParam.pageSize,
          total: total,
          showSizeChanger: true,
          showLessItems: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
          onChange: changeSize,
          onShowSizeChange: onShowSizeChange
        }"
        tableKey="base-post-index-table"
        @change="handleTableChange"
        rowKey="id"
        size="middle"
        @refresh="getList"
        :columns="columns"
        :data-source="postList"
        :loading="loading"
        :format-conditions="true"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :scroll="{ x: 1500 }"
      >
        <div class="table-operations" slot="button">
          <a-button type="primary" @click="handleAdd" v-hasPermi="['platform:post:add']"> <a-icon type="plus" />新增 </a-button>
          <a-button type="danger" v-if="!multiple" :disabled="multiple" @click="handleDelete" v-hasPermi="['platform:post:remove']"> <a-icon type="delete" />删除 </a-button>
          <a-button type="" @click="handleExport" v-hasPermi="['platform:post:export']"> <a-icon type="download" />导出 </a-button>
        </div>
        <span slot="status" slot-scope="{ record }">
          <a-badge :status="statusBage(record.status)" :text="statusFormat(record)" />
        </span>
        <span slot="anonymity" slot-scope="{ record }">
          {{ anonymityFormat(record) }}
        </span>
        <span slot="type" slot-scope="{ record }">
          <a-tag :color="typeColor(record.type)">{{ typeFormat(record) }}</a-tag>
        </span>
        <span slot="image" slot-scope="{ record }">
          <a-avatar shape="square" :src="imageUrl + record.image" />
        </span>
        <span slot="operation" slot-scope="{ record }">
          <a v-if="controlUpdate(record)" @click="handleUpdate(record)" v-hasPermi="['platform:post:add']">修改</a>
          <a-divider v-if="controlUpdate(record)" type="vertical" v-hasPermi="['platform:post:add']" />
          <a @click="handleDelete(record)" v-hasPermi="['platform:post:remove']">删除</a>
          <a-divider type="vertical" v-hasPermi="['platform:post:remove']" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多<a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleApproveRecord(record)">审核情况</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleCommentTable(record)">评论管理</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </advance-table>
    </a-card>
  </div>
</template>
<script>
import { listPost, delPost, exportPost, getInitData } from '@/api/platform/post'
import { getUserProfile } from '@/api/system/user'
import AdvanceTable from '@/components/pt/table/AdvanceTable'
import SelectUser from '@/components/pt/selectUser/SelectUser'
import SelectSection from '@/views/platform/components/SelectSection'
import SelectRegion from '@/views/platform/components/SelectRegion'
import ApproveRecordTableModal from '@views/platform/components/ApproveRecordTableModal'
import CommentTableModal from '@views/platform/components/CommentTableModal'
import PostAddForm from '@/views/platform/post/modules/PostAddForm'
import PostEditForm from '@/views/platform/post/modules/PostEditForm'
export default {
  name: 'Post',
  components: {
    AdvanceTable,
    SelectUser,
    SelectSection,
    SelectRegion,
    ApproveRecordTableModal,
    CommentTableModal,
    PostAddForm,
    PostEditForm
  },
  data() {
    return {
      //图片链接
      imageUrl: process.env.VUE_APP_BASE_API,
      showAddModal: false,
      showEditModal: false,
      showApproveRecordTableModal: false,
      showCommentTableModal: false,
      user: {},
      roleControlQuery: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的主键集合
      selectedRowKeys: [],
      // 选中的数据集合
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // label的百分比
      labelCol: { span: 6 },
      // 内容区域的百分比
      wrapperCol: { span: 18 },
      // 帖子管理表格数据
      postList: [],
      // 帖子状态字典
      statusOptions: [],
      anonymityOptions: [],
      typeOptions: [],
      //帖子ID
      postId: undefined,
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,
        regionId: undefined,
        sectionId: undefined,
        title: undefined,
        content: undefined,
        type: undefined,
        status: undefined,
        anonymity: undefined
      },
      columns: [
        {
          title: '用户',
          dataIndex: 'userName',
          ellipsis: true,
          align: 'left',
          width: '100px'
        },
        {
          title: '地区',
          dataIndex: 'regionName',
          ellipsis: true,
          align: 'left',
          width: '150px'
        },
        {
          title: '版块',
          dataIndex: 'sectionName',
          ellipsis: true,
          align: 'left',
          width: '150px'
        },
        {
          title: '帖子标题',
          dataIndex: 'title',
          ellipsis: true,
          align: 'left',
          width: '180px'
        },
        {
          title: '帖子内容',
          dataIndex: 'content',
          ellipsis: true,
          align: 'left',
          width: '250px'
        },
        {
          title: '帖子封面',
          dataIndex: 'image',
          scopedSlots: { customRender: 'image' },
          ellipsis: true,
          align: 'center',
          width: '100px'
        },
        {
          title: '联系人',
          dataIndex: 'contact',
          ellipsis: true,
          align: 'left',
          width: '80px'
        },
        {
          title: '联系电话',
          dataIndex: 'phone',
          ellipsis: true,
          align: 'left',
          width: '100px'
        },
        {
          title: '类型',
          dataIndex: 'type',
          ellipsis: true,
          align: 'center',
          width: '80px',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '匿名状态',
          dataIndex: 'anonymity',
          ellipsis: true,
          align: 'center',
          width: '80px',
          scopedSlots: { customRender: 'anonymity' }
        },
        {
          title: '帖子发布时间',
          dataIndex: 'publishTime',
          ellipsis: true,
          align: 'left',
          width: '150px'
        },
        {
          title: '帖子修改时间',
          dataIndex: 'editTime',
          ellipsis: true,
          align: 'left',
          width: '150px'
        },
        {
          title: '点赞数',
          dataIndex: 'likeNumber',
          ellipsis: true,
          align: 'center',
          width: '80px'
        },
        {
          title: '收藏数',
          dataIndex: 'collectNumber',
          ellipsis: true,
          align: 'center',
          width: '80px'
        },
        {
          title: '回复数',
          dataIndex: 'replyNumber',
          ellipsis: true,
          align: 'center',
          width: '80px'
        },
        {
          title: '浏览数',
          dataIndex: 'viewNumber',
          ellipsis: true,
          align: 'center',
          width: '80px'
        },
        {
          title: '举报数',
          dataIndex: 'reportNumber',
          ellipsis: true,
          align: 'center',
          width: '80px'
        },
        {
          title: '帖子状态',
          dataIndex: 'status',
          ellipsis: true,
          align: 'center',
          width: '120px',
          scopedSlots: { customRender: 'status' },
          fixed: 'right'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: '150px',
          scopedSlots: { customRender: 'operation' },
          fixed: 'right'
        }
      ]
    }
  },
  created() {
    this.getList()
    getInitData('approve_status,is_anonymity,post_type').then(response => {
      this.statusOptions = response.data.approve_status
      this.anonymityOptions = response.data.is_anonymity
      this.typeOptions = response.data.post_type
    })
    getUserProfile().then(response => {
      this.user = response.data.user
    })
    if (this.roleJudge()) {
      this.roleControlQuery = true
    }
  },
  methods: {
    roleJudge() {
      if (!this.$store.state.user.roles.includes('admin')) {
        return true
      }
      return false
    },
    controlUpdate(record) {
      if (this.roleJudge()) {
        if (record.userId === this.user.id) return true
        else return false
      }
      return true
    },
    handleApproveRecord(record) {
      this.postId = record.id
      this.showApproveRecordTableModal = true
      this.$nextTick(() => this.$refs.approveRecordTableModal.handleTable())
    },
    handleCommentTable(record) {
      this.postId = record.id
      this.showCommentTableModal = true
      this.$nextTick(() => this.$refs.commentTableModal.handleTable())
    },
    radioAgain(value) {
      if (this.queryParam.anonymity === value) {
        this.queryParam.anonymity = undefined
      }
    },
    /** 查询帖子管理列表 */
    getList() {
      this.loading = true
      const param = JSON.parse(JSON.stringify(this.queryParam))
      if (this.queryParam.userId) {
        param.userId = this.queryParam.userId.ids
      }
      if (this.queryParam.sectionId) {
        param.sectionId = this.queryParam.sectionId.sectionId
      }
      listPost(param).then(response => {
        this.postList = response.data.rows
        this.total = response.data.total
        this.loading = false
      })
    },
    // 帖子状态字典翻译
    statusFormat(row) {
      if (row.status) {
        return this.selectDictLabel(this.statusOptions, row.status)
      } else {
        return ''
      }
    },
    // 帖子匿名状态字典翻译
    anonymityFormat(row) {
      if (row.anonymity) {
        return this.selectDictLabel(this.anonymityOptions, row.anonymity)
      } else {
        return ''
      }
    },
    typeFormat(row) {
      if (row.type) {
        return this.selectDictLabel(this.typeOptions, row.type)
      } else {
        return ''
      }
    },
    // 类型徽标数类型
    typeColor(type) {
      if (type === '0') {
        return 'blue'
      } else if (type === '1') {
        return 'green'
      } else if (type === '2') {
        return 'red'
      }
    },
    // 帖子状态徽标数类型
    statusBage(status) {
      if (status === '0') {
        return 'default'
      } else if (status === '1') {
        return 'processing'
      } else if (status === '2') {
        return 'warning'
      } else if (status === '3') {
        return 'error'
      } else if (status === '4') {
        return 'processing'
      } else if (status === '5') {
        return 'error'
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,
        regionId: undefined,
        sectionId: undefined,
        title: undefined,
        content: undefined,
        type: undefined,
        status: undefined,
        anonymity: undefined
      }
      this.handleQuery()
    },
    /** 翻页操作 */
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    /** 翻页操作 */
    onSizeChange(current, size) {
      this.queryParam.pageNum = 1
      this.queryParam.pageSize = size
      this.getList()
    },
    /** 翻页操作 */
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    /** 翻页操作 */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map(item => item.id)
      this.single = selectedRowKeys.length !== 1
      this.multiple = !selectedRowKeys.length
    },
    /** 查询折叠和展开操作 */
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleAdd() {
      this.showAddModal = true
      this.$nextTick(() => this.$refs.postAddForm.handleAdd())
    },
    handleUpdate(record, ids) {
      this.showEditModal = true
      this.$nextTick(() => this.$refs.postEditForm.handleUpdate(record, ids))
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this
      const postIds = row.id || this.ids
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk() {
          return delPost(postIds).then(() => {
            that.onSelectChange([], [])
            that.getList()
            that.$message.success('删除成功', 3)
          })
        },
        onCancel() {}
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this
      this.$confirm({
        title: '是否确认导出?',
        content: '此操作将导出当前条件下所有数据而非选中数据',
        onOk() {
          return exportPost(that.queryParam).then(response => {
            that.download(response.msg)
            that.$message.success('导出成功', 3)
          })
        },
        onCancel() {}
      })
    },
    handleTableChange(pagination, filters, sorter) {
      if (sorter.field !== undefined && sorter.field !== null && sorter.field !== '') {
        this.queryParam.orderByColumn = 'a.' + sorter.field
        this.queryParam.isAsc = sorter.order
      }
      this.getList()
    }
  }
}
</script>
